import os.path
import json
from http.client import responses

import requests
from flask import session

import config


class WriteXhxToken:
    def __init__(self):
        # 实例化时初始化 url 和 session
        self.url = config.URL_xhx_login
        self.url_web = config.URL
        self.session = requests.session()

    def login_Xhx(self):
        # 使用实例的 session 和 url 进行登录请求
        json_data = {"serviceGroup": "sit", "username": "13221080002", "password": "123456"}
        try:
            response = self.session.post(self.url, json_data)
            if response.status_code == 200:
                return response.json().get("data")
            else:
                print(f'error:{response.status_code}')

        except requests.exceptions.RequestException as e:
            print(f'error:{e}')

        finally:
            self.session.close()

    def login_web(self):
        params = {
            "service_name": "kusercen.LoginFacade.login",
            "client_id": "6",
            "strategy": "dubbo",
            "timestamp": 1732697189951,
            "param": {
                "loginInfo": {
                    "mobileNo": "16000001001",
                    "password": "1fccb567a44880e8665b7cb9d0f97271780431ed4d2d3e768f8c79ad0fbbc1f6c6a",
                    "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
                    "clientType": "web"
                }
            }
        }
        try:
            # 发送 POST 请求
            response = self.session.post(self.url_web, json=params)

            # 确保响应成功
            if response.status_code == 200:
                responses = response.json()
                config.prints(response)
                return responses.get("data").get("resultObject").get("token")
                # 打印响应内容
                print(responses)
            else:
                print(f"Error: Received status code {response.status_code}")

        except requests.exceptions.RequestException as e:
            # 捕获请求相关的所有异常并打印
            print(f"An error occurred: {e}")

        finally:
            # 关闭会话
            self.session.close()

    def update_xhxtoken_in_json(self, new_xhxtoken,a):
        # 指定 config.json 文件路径
        config_file = os.path.join(config.BASE_DIR + "/data", 'config.json')

        try:
            # 读取 config.json 文件的内容
            with open(config_file, 'r', encoding='utf-8') as file:
                config_data = json.load(file)  # 解析 JSON 文件为字典

            # 检查是否存在 "xhx_token" 和 "xhxtoken" 键
            if "xhx_token" in config_data and "xhxtoken" in config_data["xhx_token"] and a == 1:
                # print(f"更新前的 xhxtoken: {config_data['xhx_token']['xhxtoken']}")
                # 更新 xhxtoken 的值
                config_data['xhx_token']['xhxtoken'] = new_xhxtoken
                # print(f"更新后的 xhxtoken: {new_xhxtoken}")

            elif "token" in config_data and a == 2:
                config_data["token"] = new_xhxtoken

            else:
                print("配置中未找到 xhx_token 或 xhxtoken 键")

            # 将更新后的字典写回到 config.json 文件
            with open(config_file, 'w', encoding='utf-8') as file:
                json.dump(config_data, file, indent=4, ensure_ascii=False)  # 格式化写入

            # print(f"xhxtoken 已更新为: {new_xhxtoken}")

        except Exception as e:
            print(f"更新配置文件时出错: {e}")

    def update_token_in_json(self,a):
        # 获取新 token 并更新配置文件中的 xhxtoken
        token = self.login_Xhx()
        print(f'xhx令牌：{token}')
        self.update_xhxtoken_in_json(token,a)

    def update_web_token_in_json(self,a):
        # 获取新 token 并更新配置文件中的 xhxtoken
        token = self.login_web()
        print(f'web令牌：{token}')
        self.update_xhxtoken_in_json(token,a)


if __name__ == "__main__":
    # 创建 XhxLogin 实例并更新 xhxtoken
    WriteXhxToken().update_token_in_json(1)
    # 创建 XhxLogin 实例并更新 token
    WriteXhxToken().update_web_token_in_json(2)
    # WriteXhxToken().login_web()
